package org.game.porker.porker24.mybatis.service.impl;

import java.util.Date;
import java.util.List;

import org.game.porker.porker24.mybatis.dao.GameMapper;

//import javax.annotation.Resource;

import org.game.porker.porker24.mybatis.dao.PlayerMapper;
import org.game.porker.porker24.mybatis.pojo.Game;
import org.game.porker.porker24.mybatis.pojo.Player;
import org.game.porker.porker24.mybatis.service.PlayerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service("playerService")
public class PlayerServiceImpl implements PlayerService {
	@Autowired
	private PlayerMapper playerDao;
	@Autowired
	private GameMapper gameDao;
	
	public PlayerServiceImpl() {
		// TODO Auto-generated constructor stub
	}

	public List<Player> getTop10Players() {
		// TODO Auto-generated method stub
		return playerDao.selectTop10Player();
	}

	public void addNewPlayer(Player player) {
		// TODO Auto-generated method stub
		playerDao.insertNewPlayer(player);
	}

	public Player playerLogin(String user, String password) {
		// TODO Auto-generated method stub
		Player pl  = new Player();
		pl.setLoginName(user);
		pl.setPassword(password);
		return playerDao.loginPlayer(pl);
	}

	@Transactional//事务管理？
	public void insertGameAndUpdateScore(int playerId, int score) {
		// TODO Auto-generated method stub
		Game game = new Game();
		//设置玩家id
		game.setPlayerId(playerId);
		//当前时间
		game.setFinishTime(new Date());
		//设置分数
		game.setScore(score);
		//创建游戏
		gameDao.insertGameScore(game);
		//查找该id的所有游戏
		List<Game> allgames = gameDao.selectGamesByplayerId(playerId);
		//该id玩家玩游戏的次数
		int count = allgames.size();
		//初始化总分数
		double total = 0;
		for(Game g : allgames) {
			total += g.getScore();//计算总分数
		}
		//计算平均数
		float avg = (float)(total / count);
		Player p = new Player();
		p.setPlayerId(playerId);
		p.setAvgScore(avg);
		//更新该id玩家的分数
		playerDao.updatePlayerScore(p);
	}

}
